package com.jindy.module.oaReceiveApproval.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jindy.activiti.service.IProcessService;
import com.jindy.common.constant.Constants;
import com.jindy.common.exception.base.BaseException;
import com.jindy.common.utils.DateUtils;
import com.jindy.common.utils.SecurityUtils;
import com.jindy.common.utils.StringUtils;
import com.jindy.jpush.utils.UniJpushUtils;
import com.jindy.module.approvalRecord.domain.ApprovalRecord;
import com.jindy.module.approvalRecord.mapper.ApprovalRecordMapper;
import com.jindy.module.jpush.mapper.JpushMapper;
import com.jindy.module.oaDepartApproval.domain.SyOaDepart;
import com.jindy.module.oaDepartApproval.service.impl.SyOaDepartServiceImpl;
import com.jindy.module.oacopy.service.ISyOaCopyService;
import com.jindy.module.oacopyconfig.domain.SyOaCopyConfig;
import com.jindy.module.oacopyconfig.mapper.SyOaCopyConfigMapper;
import com.jindy.module.serialNum.service.ISySerialNumTService;
import com.jindy.module.syTableRecord.service.ISyTableRecordTService;
import com.jindy.system.domain.SysUserRoleDeptInfo;
import com.jindy.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jindy.module.oaReceiveApproval.mapper.SyOaReceiveMapper;
import com.jindy.module.oaReceiveApproval.domain.SyOaReceive;
import com.jindy.module.oaReceiveApproval.service.ISyOaReceiveService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;

/**
 * 招待审批Service业务层处理
 * 
 * @author jindy
 * @date 2023-06-01
 */
@Service
public class SyOaReceiveServiceImpl implements ISyOaReceiveService 
{
    private static final Logger LOGGER = LoggerFactory.getLogger(SyOaReceiveServiceImpl.class);

    @Autowired
    private SyOaReceiveMapper syOaReceiveMapper;

    @Autowired
    private IProcessService processService;

    /**
     * 抄送Service
     */
    @Resource
    private ISyOaCopyService syOaCopyService;

    /**
     * 配置表
     */
    @Resource
    private SyOaCopyConfigMapper syOaCopyConfigMapper;

    /**
     * 生成流水单号Service
     */
    @Resource
    private ISySerialNumTService serialNumTService;

    /**
     * 生成流水单号Service
     */
    @Resource
    private ApprovalRecordMapper approvalRecordMapper;

    /**
     * 用户Service
     */
    @Resource
    private ISysUserService sysUserService;

    /**
     * 设备Mapper
     */
    @Resource
    private JpushMapper jpushMapper;

    /**
     * 存储表Service
     */
    @Resource
    private ISyTableRecordTService iSyTableRecordTService;

    /**
     * 查询招待审批
     * 
     * @param id 招待审批主键
     * @return 招待审批
     */
    @Override
    public SyOaReceive selectSyOaReceiveById(Long id)
    {
        return syOaReceiveMapper.selectSyOaReceiveById(id);
    }

    /**
     * 查询招待审批列表
     * 
     * @param syOaReceive 招待审批
     * @return 招待审批
     */
    @Override
    public List<SyOaReceive> selectSyOaReceiveList(SyOaReceive syOaReceive)
    {
        if (!SecurityUtils.isAdmin(SecurityUtils.getLoginUser().getUser().getUserId())) {
            syOaReceive.setCreateBy(SecurityUtils.getUsername());
        }
        List<SyOaReceive> list = syOaReceiveMapper.selectSyOaReceiveList(syOaReceive);
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(item -> {
                try {
                    processService.richProcessField(item);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
        return list;
//        return syOaReceiveMapper.selectSyOaReceiveList(syOaReceive);
    }

    /**
     * 新增招待审批
     * 
     * @param syOaReceive 招待审批
     * @return 结果
     */
    @Override
    public int insertSyOaReceive(SyOaReceive syOaReceive)
    {
        // 生成流水单号
        String serialNum = serialNumTService.generateSerialNum("ZDSP");
        if (StringUtils.isBlank(serialNum)) {
            throw new BaseException("新增招待审批-获取招待单号失败");
        }
        //获取申请人信息
        Long userId=SecurityUtils.getLoginUser().getUser().getUserId();
        syOaReceive.setApplyUserId(userId.toString());
        syOaReceive.setApplyUserName(SecurityUtils.getLoginUser().getUser().getUserName());

        //获取申请时间
        syOaReceive.setApplyTime(DateUtils.getNowDate());

        syOaReceive.setSerialNum(serialNum);
        syOaReceive.setBusinessStatus(Constants.DRAFT);
        syOaReceive.setCreateTime(DateUtils.getNowDate());
        iSyTableRecordTService.saveEntityAndTable(syOaReceive,serialNum);
        return syOaReceiveMapper.insertSyOaReceive(syOaReceive);
//        syOaReceive.setCreateTime(DateUtils.getNowDate());
//        return syOaReceiveMapper.insertSyOaReceive(syOaReceive);
    }

    /**
     * 修改招待审批
     * 
     * @param syOaReceive 招待审批
     * @return 结果
     */
    @Override
    public int updateSyOaReceive(SyOaReceive syOaReceive)
    {
        syOaReceive.setUpdateTime(DateUtils.getNowDate());
        return syOaReceiveMapper.updateSyOaReceive(syOaReceive);
    }

    /**
     * 批量删除招待审批
     * 
     * @param ids 需要删除的招待审批主键
     * @return 结果
     */
    @Override
    public int deleteSyOaReceiveByIds(Long[] ids)
    {
        return syOaReceiveMapper.deleteSyOaReceiveByIds(ids);
    }

    /**
     * 删除招待审批信息
     * 
     * @param id 招待审批主键
     * @return 结果
     */
    @Override
    public int deleteSyOaReceiveById(Long id)
    {
        return syOaReceiveMapper.deleteSyOaReceiveById(id);
    }

    /**
     * 提交申请
     *
     * @param syOaReceive
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void submitApply(SyOaReceive syOaReceive) throws Exception {
        // 初始化值
        Map<String, Object> variables = createVariables(syOaReceive);
        // 启动流程
        processService.submitApply(syOaReceive, "receive", variables);
        // 添加抄送人
        syOaCopyService.addCopyUsers("ZDSP", syOaReceive.getId());
        //新增审批记录
        List<Long> longs = addApprovalRecord(syOaReceive, variables);
        // 通知审批人
        sendApproveMessage(longs);
        syOaReceive.setBusinessStatus(Constants.APPROVE);
        updateSyOaReceive(syOaReceive);
    }

    /**
     * 新增审批记录
     * @param syOaReceive
     * @param map
     * @return
     */
    private List<Long> addApprovalRecord(SyOaReceive syOaReceive, Map<String, Object> map) {
        List<Long> list = new ArrayList<>();
        int sequence = 1;
        //  发起人
        ApprovalRecord firstApprovalRecord = getApprovalRecord(syOaReceive);
        firstApprovalRecord.setSequence(sequence);
        firstApprovalRecord.setApprovalStatus(Constants.COMPLETED);
        firstApprovalRecord.setTypeOperation(Constants.AGREE);
        firstApprovalRecord.setBusinessStatus(Constants.APPROVE);
        firstApprovalRecord.setApproverId(Long.valueOf(syOaReceive.getApplyUserId()));
        firstApprovalRecord.setApproverName(syOaReceive.getApplyUserName());
        approvalRecordMapper.insertApprovalRecord(firstApprovalRecord);

        //不是主管，则需要主管审批
        if (!(boolean)map.get("isdeptleader")){
            sequence++;
            //  第一审批人
            ApprovalRecord secondApprovalRecord = getApprovalRecord(syOaReceive);
            secondApprovalRecord.setSequence(sequence);
            secondApprovalRecord.setApprovalStatus(Constants.APPROVE);
            String deptleaderId=map.get("deptleaderId").toString();
            secondApprovalRecord.setApproverId(Long.parseLong(deptleaderId));
            secondApprovalRecord.setApproverName((String) map.get("deptleader"));
            approvalRecordMapper.insertApprovalRecord(secondApprovalRecord);
            list.add(Long.parseLong(deptleaderId));
        }

        sequence++;
        //  第二审批人
        ApprovalRecord fifthApprovalRecord = getApprovalRecord(syOaReceive);
        fifthApprovalRecord.setSequence(sequence);
        fifthApprovalRecord.setApprovalStatus(Constants.APPROVE);
        String bossId=map.get("bossId").toString();
        fifthApprovalRecord.setApproverId(Long.parseLong(bossId));
        fifthApprovalRecord.setApproverName((String) map.get("boss"));
        approvalRecordMapper.insertApprovalRecord(fifthApprovalRecord);
        list.add(Long.parseLong(bossId));

        return list;
    }

    /**
     * 获取审批记录对象
     *
     * @param syOaReceive
     * @return
     */
    private ApprovalRecord getApprovalRecord(SyOaReceive syOaReceive) {
        ApprovalRecord approvalRecord = new ApprovalRecord();
        approvalRecord.setSerialNum(syOaReceive.getSerialNum());
        approvalRecord.setUserId(Long.valueOf(syOaReceive.getApplyUserId()));
        approvalRecord.setOrderId(syOaReceive.getId());
        approvalRecord.setUserName(syOaReceive.getApplyUserName());
        approvalRecord.setUpdateTime(DateUtils.parseDate(DateUtils.getTime()));
        approvalRecord.setUpdateBy(syOaReceive.getApplyUserName());
        approvalRecord.setCreateBy(syOaReceive.getApplyUserName());
        approvalRecord.setCreateTime(DateUtils.parseDate(DateUtils.getTime()));
        return approvalRecord;
    }

    /**
     * 逻辑流初始化
     *
     * @param syOaReceive
     * @return
     */
    public Map<String, Object> createVariables(SyOaReceive syOaReceive) {
        Map<String, Object> var = new HashMap<>(500);
        // 判断申请人是否是主管
        List<SysUserRoleDeptInfo> userList = sysUserService.selectUsersByUserName(syOaReceive.getApplyUserName());
        if (CollectionUtils.isEmpty(userList)) {
            throw new BaseException("招待审批-判断是否为直接主管集合为空");
        }

        //申请人不是主管，则先由部门主管审批
        if (!userList.get(0).getUserName().equals(userList.get(0).getLeader())){
            var.put("isdeptleader", false);
            var.put("deptleader",userList.get(0).getLeader());
            var.put("deptleaderId",userList.get(0).getLeaderId());
        }
        else{
            var.put("isdeptleader", true);
        }

        //boss审批
        SyOaCopyConfig syOaCopyConfig3=new SyOaCopyConfig();
        syOaCopyConfig3.setNumber("ZDSP_LEADER");
        List<SyOaCopyConfig> syOaCopyConfigs3=syOaCopyConfigMapper.selectSyOaCopyConfigList(syOaCopyConfig3);
        if (CollectionUtils.isEmpty(syOaCopyConfigs3)) {
            throw new BaseException("createVariables", "招待审批获取老板负责人失败");
        }
        var.put("boss",syOaCopyConfigs3.get(0).getCopyUserName());
        var.put("bossId",syOaCopyConfigs3.get(0).getCopyUserId());

        return var;
    }

    /**
     * 给审批人推送消息
     * @param addJpushList
     */
    private void sendApproveMessage(List<Long> addJpushList) {
        try {
            List<String> addRegIds = jpushMapper.selectRegistrationIdsByUserIds(addJpushList);
            if (!CollectionUtils.isEmpty(addRegIds)){
                UniJpushUtils.sendApproveMessage(addRegIds);
            }
        } catch (Exception e) {
            LOGGER.error("离职审批审批人推送通知失败",e);
        }
    }

}
